﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SwaggerSdk
{
    public class HttpGather
    {
        private readonly HttpClient _httpClient;
        public HttpGather(HttpClient httpClient)
        {
            _httpClient = httpClient;

            //_httpClient.BaseAddress = new Uri(_baseUrl);
            //// 设置请求头
            //_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
        }
        #region 单个汉字采集
        /// <summary>
        /// 汉字查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<RspWord> GetWordAsync(string keyword)
        {
            string url = $"https://www.hanyuguoxue.com/zidian/search?words={HttpUtility.UrlEncode(keyword)}&type=all";
            var response = await _httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                response.EnsureSuccessStatusCode();
                string htmlUrl = response.RequestMessage.RequestUri.AbsoluteUri.ToString();
                var rspcontent = await response.Content.ReadAsStringAsync();
                return GetWord(rspcontent, htmlUrl);
            }
            return null;
        }

        public async Task<RspWord> GetWordAsync(int page)
        {
            string url = $"https://www.hanyuguoxue.com/zidian/zi-{page}";
            var response = await _httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                response.EnsureSuccessStatusCode();
                var rspcontent = await response.Content.ReadAsStringAsync();
                return GetWord(rspcontent, url);
            }
            return null;
        }
        /// <summary>
        /// 汉字处理
        /// </summary>
        /// <param name="rspcontent"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private RspWord GetWord(string rspcontent, string url)
        {
            try
            {
                string html = RegexHelp.SniffwebFirstCode(rspcontent, "main-content", "main-sidebar");
                string html1 = RegexHelp.SniffwebFirstCode(html, "<div class=\"card pb-3\" data-id=基本信息>", "<div class=card data-id=笔顺>");
                RspWord obj = new RspWord();
                obj.F_Name = RegexHelp.SniffwebFirstCode(html, "<div class=zi-title-main><h2>", "</h2>");
                obj.F_PinYin = RegexHelp.SniffwebForCode(html1, "<em class=py>", "</em>", '|');
                obj.F_BuShou = RegexHelp.SniffwebFirstCode(html1, "title=部首", "的汉字");
                obj.F_ZongBiHua = RegexHelp.SniffwebFirstCode(html1, "title=总笔画", "的汉字");
                obj.F_BiHua = RegexHelp.SniffwebFirstCode(html1, "部外笔画", "</p>");
                obj.F_BiHua = RegexHelp.SniffwebFirstCode(obj.F_BiHua, "<span>", "画");
                obj.F_JieGou = RegexHelp.SniffwebFirstCode(html1, "<label>结构</label>", "</p>");
                obj.F_JieGou = RegexHelp.SniffwebFirstCode(obj.F_JieGou, "<span>", "</span>");
                obj.F_ZaoZiFa = RegexHelp.SniffwebFirstCode(html1, "<label>造字法</label>", "</p>");
                obj.F_ZaoZiFa = RegexHelp.SniffwebFirstCode(obj.F_ZaoZiFa, "<span>", "</span>");
                obj.F_Tongyima = RegexHelp.SniffwebFirstCode(html1, "<label>统一码</label>", "</p>");
                obj.F_Tongyima = RegexHelp.SniffwebFirstCode(obj.F_Tongyima, "<span>", "</span>");
                obj.F_JinYiCi = RegexHelp.SniffwebFirstCode(html1, "<label>近义词</label>", "</p>");
                obj.F_JinYiCi = RegexHelp.SniffwebForCode(obj.F_JinYiCi, "title=", ">", '，');
                obj.F_FanYiCi = RegexHelp.SniffwebFirstCode(html1, "<label>反义词</label>", "</span>");
                obj.F_FanYiCi = RegexHelp.SniffwebForCode(obj.F_FanYiCi, "title=", ">", '，');
                obj.F_ChaiZi = RegexHelp.SniffwebFirstCode(html, "<div class=\"zi-summary show-more-container\">", "仓颉码");
                obj.F_ChaiZi = RegexHelp.SniffwebFirstCode(obj.F_ChaiZi, "可拆字为“<em>", "</em>");
                obj.F_Url = url;
                obj.F_Html = html;
                return obj;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        #endregion

        #region 词语采集
        /// <summary>
        /// 词语查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<RspWords> GetWordsAsync(string keyword)
        {
            string url = $"https://www.hanyuguoxue.com/cidian/search?words={HttpUtility.UrlEncode(keyword)}";
            var response = await _httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                response.EnsureSuccessStatusCode();
                string htmlUrl = response.RequestMessage.RequestUri.AbsoluteUri.ToString();
                var rspcontent = await response.Content.ReadAsStringAsync();
                return GetWords(rspcontent, htmlUrl);
            }
            return null;
        }
        private RspWords GetWords(string rspcontent, string url)
        {
            try
            {
                string html = RegexHelp.SniffwebFirstCode(rspcontent, "<div class=card>", "<div class=\"card py-3\">");

                //string html1 = RegexHelp.SniffwebFirstCode(html, "<div class=\"ci-attrs mb-3\">", "<div class=ci-content-title>");
                string html1 = RegexHelp.SniffwebFirstCode(rspcontent, "name=robots>", "name=description>");
                RspWords obj = new RspWords();
                obj.F_Name = RegexHelp.SniffwebFirstCode(html1, "content=\"", "的拼音");
                obj.F_PinYin = RegexHelp.SniffwebFirstCode(html1, "拼音是：", "，");
                obj.F_CiXing = RegexHelp.SniffwebFirstCode(html1, obj.F_PinYin+ "，", "。");
                obj.F_JinYiCi = RegexHelp.SniffwebFirstCode(html1, "近义词有：", "。");
                obj.F_FanYiCi = RegexHelp.SniffwebFirstCode(html1, "反义词有：", "。");
                obj.F_FanTi = RegexHelp.SniffwebFirstCode(html, "繁体</label>", "</p>");
                if (!string.IsNullOrEmpty(obj.F_FanTi))
                    obj.F_FanTi = RegexHelp.SniffwebFirstCode(obj.F_FanTi, "<span>", "</span>");
                obj.F_JieShi = RegexHelp.SniffwebFirstCode(html1, "解释是：", "近义词有");
                if (string.IsNullOrEmpty(obj.F_JieShi))
                    obj.F_JieShi = RegexHelp.SniffwebFirstCode(html1, "解释是：", "。");
                
                obj.F_Url = url;
                obj.F_Html = html;
                return obj;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        #endregion


        private T CallBackResult<T>(string rspcontent)
        {
            if (string.IsNullOrEmpty(rspcontent))
            {
                throw new InvalidOperationException("异常:返回值为空");
            }
            var result = JsonConvert.DeserializeObject<T>(rspcontent);
            if (result == null)
            {
                throw new InvalidOperationException("异常:返回值为空");
            }

            return result;
        }

        private string BuildUrlWithParams(string endpoint, Dictionary<string, string> queryParams)
        {
            if (queryParams == null || queryParams.Count == 0)
                return endpoint;

            var queryString = string.Join("&", queryParams.Select(kv => $"{kv.Key}={WebUtility.UrlEncode(kv.Value)}"));
            return $"{endpoint}?{queryString}";
        }
    }
}
